import React, { PureComponent, Children } from 'react'
import { findDOMNode } from 'react-dom'

export default class OuterClickWrapper extends PureComponent {
  componentDidMount() {
    document.addEventListener('click', this.handleOutterClick)
  }
  componentWillUnmount() {
    document.removeEventListener('click', this.handleOutterClick)
  }
  render() {
    return Children.only(this.props.children)
  }
  handleOutterClick = event => {
    const { onClick } = this.props
    if (!onClick) {
      return
    }
    const root = findDOMNode(this)
    const isContains = this.contains(root, event.target)
    if (!isContains) {
      onClick(event)
    }
  }
  contains(rootNode, node) {
    if ('function' === typeof rootNode.contains) {
      return rootNode.contains(node)
    }
  }
}